package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.web.feign.SeckillProductFeginApi;
import cn.wolfcode.redis.SeckillRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
@Setter@Getter
@RefreshScope
@Slf4j
public class MyInitSeckillProductJob implements SimpleJob {
    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Autowired
    private SeckillProductFeginApi seckillProductFeginApi;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void execute(ShardingContext shardingContext)
    {
        System.out.println(shardingContext.getShardingParameter());
        doWork(shardingContext.getShardingParameter());
    }

    private void doWork(String type) {
        //远程调用秒杀服务查询数据
        Result<List<SeckillProductVo>> result = seckillProductFeginApi.selectByTypes(Integer.parseInt(type));
        if (result!=null&&!result.hasError()) {
            //2把查询到的数据放到redis中
            List<SeckillProductVo> seckillProductVoList = result.getData();
            for (SeckillProductVo seckillProductVo : seckillProductVoList) {
                stringRedisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_PRODUCT_LIST.getRealKey(type),
                        seckillProductVo.getId() + "",
                        JSON.toJSONString(seckillProductVo));
                //存入商品数量,为控制访问人数做铺垫
                stringRedisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(type),
                        seckillProductVo.getId()+"",
                        seckillProductVo.getStockCount()+"");
            }
        }
    }
}
